import axios from 'axios'
import vm from '../main'
import { baseApi } from '../config'
import router from '../router/index';
import {signBySHA256WithRSA,privateKey,wxuuid} from "./cryptoUtils";
let obj = {}
/* 全局默认配置 */
var http = axios.create({
  baseURL: baseApi,
  timeout: 5000
})
function havSign(uri){
  let startIndex = uri.indexOf('/association-api');
  let result = uri.substring(startIndex);
  if (result.includes('?')) {
    result = result.split('?')[0];
  } else {
    result = result;
  }
  return new Promise((resolve,reject)=>{
    let timestamp = Date.now() + ''
    let nonce = wxuuid()
    let str = {"timestamp":timestamp,"nonce":nonce,"uri":result}
    let signature = ''
    signBySHA256WithRSA(privateKey,JSON.stringify(str)).then(res=>{
      signature = res
      let obj = {
        timestamp,nonce,signature
      }
      resolve(obj)
    })
  })
}
/* 请求拦截器 */
http.interceptors.request.use(
  async config => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    config.headers.timestamp = Math.floor(new Date().getTime() / 1000)
    config.headers.Authorization = sessionStorage.getItem('token') || ''
    let uri = config.baseURL + config.url
    // 加签开始
    obj = await havSign(uri)
    config.headers.nonce = obj.nonce
    config.headers.timestamp = obj.timestamp
    config.headers.sign = obj.signature
    // put delete 转为post
    if(['put', 'delete'].includes(config.method)) {
      let newParams = {'_method':config.method};
      if(config.params) {
        newParams = {...newParams,...config.params};
      }
      config.params = newParams;
      config.method = 'post';
    }
    // 接口没返回时显示loadin
    if (config.loading === true) {
      vm.$loading.hide()
      vm.$loading.show()
    }
    return config
  },
  error => {
    vm.$loading.hide()
    return Promise.reject(error)
  }
)
/* 响应拦截器 */
http.interceptors.response.use(
  res => {
    vm.$loading.hide()
    return res
  },
  error => {
    let {status} = error.response;
       //未登录状态
      //  if (status === 401) {
      //   vm.$toast({
      //     msg: "无权限的请求，需重新登录",
      //     type: "fail",
      //   });
      //   vm.$router.push('/login');
      //   return;
      // }
    vm.$loading.hide()
    return Promise.reject(error)
  }
)

function get (url, data, loading) {
  return new Promise((resolve, reject) => {
    http.get(url,data).then(
      response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}

function post (url, data, loading) {
  return new Promise((resolve, reject) => {
    http.post(url, data, { loading: loading }).then(
      response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}
function Del (url, data, loading) {
  return new Promise((resolve, reject) => {
    http.delete(url,data).then(
      response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}
export { http, get, post,Del }
